package com.example.mytestdemo.view.view

import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.FrameLayout
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.lifecycleScope
import com.example.mytestdemo.R
import com.example.mytestdemo.databinding.BaseViewCurrentTimeLayoutBinding

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.launch
import java.util.*

/**
 * @author tgw
 * @date 2021/11/23
 * @describe toolbar 顶部的自定义更新时间的布局
 */
class CurrentTimeLayout @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {

    companion object {
        private const val TIME: Long = 60 * 1000
    }

    private var mBind: BaseViewCurrentTimeLayoutBinding = DataBindingUtil.inflate(
        LayoutInflater.from(context),
        R.layout.base_view_current_time_layout,
        this,
        true
    )

    //计算首次还有多久更新时间
    private var firstSecond: Long = 10 * 1000

    //首次进入，用于辅助判断，当前时间距离下一分钟
    private var isCreated = true

    init {
        mBind.viewModel = parseTime()
    }

    private val countDownData = flow<Unit> {
        while (true) {
            if (isCreated) {
                delay(firstSecond)
                isCreated = false
            } else {
                delay(TIME)
            }
            emit(Unit)
        }
    }.flowOn(Dispatchers.IO)

    fun checkTimeChange(lifecycleOwner: LifecycleOwner) {
        val c1 = Calendar.getInstance()
        val second = c1[Calendar.SECOND]
        firstSecond = (60 - second) * 1000L
        lifecycleOwner.lifecycleScope.launch(Dispatchers.Main) {
            countDownData.collect {
                mBind.viewModel = parseTime()
            }
        }
    }

    private fun parseTime(): CurrentTimeBean {
        val c1 = Calendar.getInstance()
        // 获得年份
        val year = c1[Calendar.YEAR]
        // 获得月份
        val month = c1[Calendar.MONTH] + 1
        // 获得日期
        val date = c1[Calendar.DATE]
        // 获得小时
        val hour = c1[Calendar.HOUR_OF_DAY]
        // 获得分钟
        val minuteInt = c1[Calendar.MINUTE]
        var minuteString = minuteInt.toString()
        if (minuteInt < 10) {
            minuteString = "0$minuteInt"
        }
        // 获得秒
        val second = c1[Calendar.SECOND]
        // 获得星期几（注意（这个与Date类是不同的）：1代表星期日、2代表星期1、3代表星期二，以此类推）
        val day = c1[Calendar.DAY_OF_WEEK]
        return CurrentTimeBean("$hour:$minuteString", "$year-$month-$date", getWeek(day))
    }

    private fun getWeek(day: Int): String {
        var week = ""
        when (day) {
            Calendar.SUNDAY -> {
                week = "星期日"
            }
            Calendar.MONDAY -> {
                week = "星期一"
            }
            Calendar.TUESDAY -> {
                week = "星期二"
            }
            Calendar.WEDNESDAY -> {
                week = "星期三"
            }
            Calendar.THURSDAY -> {
                week = "星期四"
            }
            Calendar.FRIDAY -> {
                week = "星期五"
            }
            Calendar.SATURDAY -> {
                week = "星期六"
            }
        }
        return week
    }

    inner class CurrentTimeBean(val time: String, val date: String, val week: String)

    override fun onFinishInflate() {
        super.onFinishInflate()

    }
}





